import os
import tkinter
import tkinter.filedialog
import time
import threading
import pygame

root = tkinter.Tk()
root.title('音乐播放器v1.0')
root.geometry('600x400+500+100')
root.resizable(False,False)
folder = ''#文件路径
res = []
num = 0
now_music = ''
def buttonChooseClik():
	global folder
	global res
	if not folder:
		folder = tkinter.filedialog.askdirectory()#选择目录
		musics = [folder + '\\' +music
				  for music in os.listdir(folder)\
				  \
				  if music.endswith(('.mp3','.wav','.ogg','.m4a'))]
		ret = []
		for i in musics:
			ret.append(i.split('\\')[1:])
			res.append(i.replace('\\','/'))
		var2 = tkinter.StringVar()
		var2.set(ret)
		#列表框
		lb = tkinter.Listbox(root,listvariable=var2)
		lb.place(x=50,y=50,width=260,height=300)
	if not folder:
		return
	global playing
	playing = True
	#根据情况禁用和启用相应的按钮
	buttonPlay['state'] = 'normal'
	buttonStop['state'] = 'normal'
	pause_resume.set('播放')



#播放音乐的函数
def play():
	#初始化设备
	if len(res):
		pygame.mixer.init()
		global  num
		while playing:
			if not pygame.mixer.music.get_busy():
				#s随机播放一首歌曲
				nextMusic = res[num]
				print(nextMusic)
				print(num)
				pygame.mixer.music.load(nextMusic.encode())
				#播放一次
				pygame.mixer.music.play(1)
				#print(len(res)-1)
				if len(res) - 1 ==num:
					num = 0
				else:
					num = num + 1
				nextMusic = nextMusic.split('\\')[1:]
				musicName.set('playing...' + ''.join(nextMusic))
			else:
				time.sleep(0.1)









#点击进行播放
def bottonPlayClik():
	buttonNext['state'] = 'normal'
	buttonPrev['state'] = 'normal'
	#选择要播放的音乐文件夹
	if pause_resume.get() == '播放':
		pause_resume.set('暂停')
		global folder
		if not folder:
			#选择目录，返回目录名
			folder = tkinter.filedialog.askdirectory()
		if not folder:
			return
		global playing
		playing = True
		#

		#创建一个线程来播放音乐，当前主线程来接收用户操作
		t = threading.Thread(target=play)
		t.start()
	elif pause_resume.get() == '暂停':
		#继续音乐播放
		pygame.mixer.music.pause()
		pause_resume.set('继续')

	elif pause_resume.get() == '继续':
		#暂停音乐播放
		pygame.mixer.music.unpause()
		pause_resume.set('暂停')






#停止播放函数
def bottonStopClik():
	global playing
	playing = False
	pygame.mixer.music.stop()

#下一首
def bottonNextClik():
	global playing
	playing = False
	pygame.mixer.music.stop()

	global num
	if len(res) == num:
		num = 0
	playing = True

	#创建一个线程来播放音乐，当前主线程用来接收用户操作
	t = threading.Thread(target=play)
	t.start()

#下一首
def bottonPrevClik():
	global playing
	playing = False
	global num
	if num == 0:
		num = len(res) -2
	elif num == len(res) - 1:
		num -= 2
	else:
		num -=2
	print(num)
	playing = True

	# 创建一个线程来播放音乐，当前主线程用来接收用户操作
	t = threading.Thread(target=play)
	t.start()

#关闭窗口
def closeWindow():
	global playing
	playing = False
	time.sleep(0.3)
	try:
		#停止播放，如果已停止
		#再次停止会抛出异常，所以放在异常处理结构中
		pygame.mixer.music.stop()
		pygame.mixer.quit()
	except:
		pass
	root.destroy()



#声音的控制
def control_voice(value=0.5):
	pygame.mixer.music.set_volume(float(value))




#关闭窗口
root.protocol('WM_DELETE_WINDOW',closeWindow)








#root.protocol('')
#添加按钮

bottonChoose = tkinter.Button(root,text='添加',command=buttonChooseClik)
bottonChoose.place(x=340,y=240,width=50,height=20)
#播放按钮
pause_resume = tkinter.StringVar(root,value='播放')
buttonPlay = tkinter.Button(root,textvariable=pause_resume,command=bottonPlayClik)
buttonPlay.place(x=500,y=110,width=60,height=40)
buttonPlay['state'] = 'disabled'

#停止按钮
buttonStop = tkinter.Button(root,text='停止',command=bottonStopClik)
buttonStop.place(x=500,y=200,width=60,height=40)
buttonStop['state'] = 'disabled'



#下一首
buttonNext = tkinter.Button(root,text='下一首',command=bottonNextClik)
buttonNext.place(x=340,y=95,width=50,height=20)
buttonNext['state'] = 'disabled'


#上一首
buttonPrev = tkinter.Button(root,text='上一首',command=bottonPrevClik)
buttonPrev.place(x=340,y=155,width=50,height=20)
buttonPrev['state'] = 'disabled'

#显示内容
musicName = tkinter.StringVar(root,value='暂时没有播放音乐...')
labelName = tkinter.Label(root,textvariable=musicName)
labelName.place(x=10,y=30,width=260,height=20)

#音量
s = tkinter.Scale(root,label='音量',from_=0,to=1,orient=tkinter.HORIZONTAL,
				  length=240,showvalue=0,tickinterval=2,resolution=0.1,command=control_voice)
s.place(x=350,y=350,width=200)




root.mainloop()


